import 'package:flutter/material.dart';
import 'package:gitcode_pocket_tool/core/gitcode_api.dart';
import 'package:gitcode_pocket_tool/core/app_config.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key});

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  final GitCodeApiClient _apiClient = GitCodeApiClient();
  GitCodeUser? _currentUser;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadUserProfile();
  }

  Future<void> _loadUserProfile() async {
    setState(() {
      _isLoading = true;
    });

    try {
      // 为了演示，我们使用一个模拟的用户名
      final user = await _apiClient.fetchUser(
        'demo_user',
        personalToken: AppConfig.demoToken,
      );

      setState(() {
        _currentUser = user;
      });
    } catch (e) {
      setState(() {
        // 如果获取失败，使用模拟数据
        _currentUser = GitCodeUser(
          login: 'demo_user',
          avatarUrl: 'https://via.placeholder.com/150',
          name: '演示用户',
          bio: '这是一个演示账号',
          publicRepos: 12,
          followers: 56,
          following: 42,
        );
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _refreshUserProfile() async {
    await _loadUserProfile();
  }

  Widget _buildUserInfoSection() {
    return Column(
      children: [
        Center(
          child: Stack(
            children: [
              CircleAvatar(
                backgroundImage: NetworkImage(_currentUser!.avatarUrl),
                radius: 50,
              ),
              Positioned(
                bottom: 0,
                right: 0,
                child: Container(
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    shape: BoxShape.circle,
                  ),
                  padding: const EdgeInsets.all(4),
                  child: const Icon(Icons.camera_alt, color: Colors.grey),
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        Text(
          _currentUser!.name ?? _currentUser!.login,
          style: const TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 20,
          ),
        ),
        Text(
          '@${_currentUser!.login}',
          style: const TextStyle(color: Colors.grey),
        ),
        if (_currentUser!.bio != null && _currentUser!.bio!.isNotEmpty) ...[
          const SizedBox(height: 12),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 32),
            child: Text(
              _currentUser!.bio!,
              textAlign: TextAlign.center,
              style: const TextStyle(fontSize: 14),
            ),
          ),
        ],
        const SizedBox(height: 24),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Column(
              children: [
                Text(
                  _currentUser!.publicRepos?.toString() ?? '0',
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20,
                  ),
                ),
                const Text('仓库'),
              ],
            ),
            Column(
              children: [
                Text(
                  _currentUser!.followers?.toString() ?? '0',
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20,
                  ),
                ),
                const Text('粉丝'),
              ],
            ),
            Column(
              children: [
                Text(
                  _currentUser!.following?.toString() ?? '0',
                  style: const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20,
                  ),
                ),
                const Text('关注'),
              ],
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildMenuSection() {
    final menuItems = [
      {
        'icon': Icons.person_outline,
        'title': '个人资料',
        'onTap': () {},
      },
      {
        'icon': Icons.settings_outlined,
        'title': '设置',
        'onTap': () {},
      },
      {
        'icon': Icons.help_outline,
        'title': '帮助与反馈',
        'onTap': () {},
      },
      {
        'icon': Icons.info_outline,
        'title': '关于',
        'onTap': () {},
      },
    ];

    return ListView.separated(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: menuItems.length,
      separatorBuilder: (context, index) => const Divider(),
      itemBuilder: (context, index) {
        final item = menuItems[index];
        return ListTile(
          leading: Icon(item['icon'] as IconData),
          title: Text(item['title'] as String),
          trailing: const Icon(Icons.chevron_right),
          onTap: item['onTap'] as VoidCallback,
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的'),
      ),
      body: RefreshIndicator(
        onRefresh: _refreshUserProfile,
        child: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : _currentUser != null
                ? SingleChildScrollView(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      children: [
                        _buildUserInfoSection(),
                        const SizedBox(height: 32),
                        Card(
                          child: _buildMenuSection(),
                        ),
                        const SizedBox(height: 24),
                        ElevatedButton(
                          onPressed: () {},
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.red,
                            minimumSize: const Size(double.infinity, 48),
                          ),
                          child: const Text('退出登录'),
                        ),
                      ],
                    ),
                  )
                : const Center(child: Text('无法加载用户信息')),
      ),
    );
  }
}
